<script setup>
import { computed, reactive, watch, inject, ref } from "vue";
import {
  QuestionCircleOutlined,
  PlusOutlined
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { uniqBy } from "lodash-es";
import moment from "moment";
import { useDebounceFn } from "@vueuse/core";
import dayjs from "dayjs";
import { useVModel } from "@vueuse/core";
import { Form, message } from "ant-design-vue";
// 添加描述抽屉
import AddDecDrawer from './AddDecDrawer.vue'
const AddDecDrawerRef = ref()

const { convertTimeToTimezone ,disabledDate,disabledDateTime,getTimezoneList,currentTimezone} = inject('timezone')
const timezones = getTimezoneList()
const currentTimezoneLabel = computed(() => {
  return timezones.find((item) => item.value == currentTimezone.value).label
})
const props = defineProps({
  formData: {
    type: Object,
    default: () => {
      return {
        title: "",
        cover_img: [],
        is_private: 0,
        publishType: 1,
        fix_at: null,
        hash_tag: [],
        utc_offset:'',
        poi_id_info: {},
      };
    },
  },
  accountId: {
    type: [Number, String],
    required: true,
  },
  title: {
    type: String,
    default: "",
  },
  content: {
    type: String,
    default: "",
  },
  isShowPublishTime: {
    //是否显示发布时间
    type: Boolean,
    default: true,
  },
  group_account_list: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  previewImage: "",
  previewVisible: false,
  publishTime: "",

  topicList: [],
  selectTopicList: [],
  totalTopicList: [],
  isRequired: false,
  addressList:[],
  keyword:'',
});
const useForm = Form.useForm;
const emits = defineEmits(["update:formData"]);
const formRef = useVModel(props, "formData", emits);
formRef.value.utc_offset = currentTimezone.value
const getTopicList = async (keyword = "") => {
  const { result } = await request.post(
    "/work_ai",
    "/org/platform/account/topic",
    { id: props.accountId, keyword }
  );
  state.topicList = result;
  state.totalTopicList.push(...state.topicList);
  state.totalTopicList = uniqBy(state.totalTopicList, "key");
};


// 添加作品描述
const addDec = () => {
    // const des = formRef.
   console.log(formRef.value.des,'什么冬休???/');
    const des = JSON.parse(JSON.stringify(formRef.value.des))
    AddDecDrawerRef.value?.open(JSON.parse(JSON.stringify(des)))
}

const handleChange = (e) => {
  if (e.length) {
    formRef.value.hash_tag = state.totalTopicList.filter((item) =>
      e.includes(item.key)
    );
  }
  if (e && e.length > 19) {
    message.warning("最多选择20个话题");
  }
};
const handleAddressChange = (ids) => {
  console.log(ids, 'change的id===========');
  
  // let info = state.addressList.find(item=>item.poi_id == id)
  let infos = state.addressList.filter(ele => {
    return ids.includes(ele.poi_id)
  })
  if (infos.length) {
    formRef.value.poi_id_info = infos.map(ele => {
      return {
        poi_id: ele.poi_id,
        subname: ele.full_address,
        poi_type: ele.poi_type,
        name: ele.name,
      }
    })
    console.log(formRef.value.poi_id_info,'挂载的地点???????');
    
    // formRef.value.poi_id_info = {
    //   poi_id: info.poi_id,
    //   subname: info.full_address,
    //   poi_type: info.poi_type,
    //   name: info.name,
    // } 
  }
}
const debouncedFn = useDebounceFn((e) => {
  getTopicList(e);
}, 500);
const debouncedAdressFn = useDebounceFn((e) => {
  getAddressList(e);
}, 500);

const handleSearch = (keyword) => {
  debouncedFn(keyword);
  
};
let validate_time = () => {
  if (formRef.value.publishType == 2 && !formRef.value.fix_at) {
    return Promise.reject("请选择发布时间");
  } else {
    return Promise.resolve();
  }
};
const rulesRef = reactive({
  fix_at: [
    {
      required: true,
      validator: validate_time,
      trigger: "change",
    },
  ],
});

const { resetFields, validate, validateInfos } = useForm(formRef, rulesRef);

watch(
  () => props.formData.fix_at,
  () => {
    if (props.formData.publish_type == 2) {
      state.publishTime = props.formData.fix_at
        ? moment(props.formData.fix_at)
        : moment();
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => props.accountId,
  () => {
    props.accountId&&getTopicList();
    props.accountId&&getAddressList();
  }
);
watch(
  () => formRef.value.publishType,
  (val) => {
    if (val == 2) {
      validate(["fix_at"]);
    }
  }
);
const onTimeChange = (e) => {
  if(!e){
    state.publishTime = null
    formRef.value.fix_at = null
    return
  }
  // const offsetInMinutes = currentTimezone * 60
  //   // 将时间转换为指定时区时间
  // nextTick(()=>{
  //   state.publishTime = dayjs(e).utcOffset(offsetInMinutes)
  // })

  // formRef.value.fix_at = e ? dayjs(e).utcOffset(offsetInMinutes).format('YYYY-MM-DD HH:mm') : null
  state.publishTime = dayjs(e)
  formRef.value.fix_at = e ? dayjs(e).format('YYYY-MM-DD HH:mm') : null
};
const validateData = () => {
  return new Promise((resolve, reject) => {
    validate()
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
defineExpose({
  validateData,
});
const getAddressList = async (keyword)=>{
  let params = {
    latitude: 31.834099748099174,
    longitude: 117.20528722621872,
    id:props.accountId,
    keyword,
  }
  request.post("/work_ai", "/org/platform/account/poid", params).then((res) => {
    if (!res?.result?.poi_list) return 
      state.addressList = res.result.poi_list.map(item=>{
        return {
          label:item.full_address,
          value:item.poi_id,
          ...item
        }
      })

 })

}

// 组件 更新作品描述
const updateDec = (des) => {
    formRef.value.des = des
}

const handleAdressSearch = (keyword)=>{
  debouncedAdressFn(keyword)
  
}
</script>

<template>
  <div class="xiaohongshu-form">
    <a-form layout="vertical">
                  <!-- 添加成片标题按钮 -->
                
<div class="dec_list"> 
<div class="dec_item" @click="addDec" v-for="(item,index) in formRef.des" :key="index">
    <a-tooltip>
        <template #title>点击进行编辑</template>
        <span>{{ item }}</span>
    </a-tooltip>
</div>
</div>
<a-button
    style="margin: 10px 0"
    block
    type="dashed"
    @click="addDec"
    ><PlusOutlined />添加作品标题</a-button
  >
      <a-form-item >
        <template #label>
            <span class="mr-5">话题</span>
            <a-tooltip>
                <template #title>
                    <span>需要先选择账号</span>
                </template>
                <QuestionCircleOutlined />
            </a-tooltip>
         </template>
        <a-select
          v-model:value="state.selectTopicList"
          :disabled="!accountId"
          show-search
          @search="handleSearch"
          :filter-option="false"
          @change="handleChange"
          mode="multiple"
          :maxTagCount="20"
          placeholder="请选择话题"
        >
          <a-select-option
            :disabled="
              state.selectTopicList.length > 19 &&
              !state.selectTopicList.includes(item.key)
            "
            :value="item.key"
            v-for="(item, index) in state.topicList"
            :key="item.key"
            >{{ item.name }}</a-select-option
          >
        </a-select>
        <div class="mt-5 text-gray-6">您可以添加20个话题</div>
      </a-form-item>
      <a-form-item label="添加地点">
        <a-select
          v-model:value="value"
          show-search
          placeholder="添加地点"
          mode="multiple"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          :options="state.addressList"
          @search="handleAdressSearch"
          @change="handleAddressChange"
        ></a-select>
      </a-form-item>
      <a-form-item label="权限设置" required>
        <a-radio-group v-model:value="formRef.is_private">
          <a-radio :value="0">公开（所有人可见）</a-radio>
          <a-radio :value="1">私密（仅自己可见）</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="发布时间" required v-if="isShowPublishTime">
        <a-radio-group v-model:value="formRef.publishType">
          <a-radio :value="1">立即发布</a-radio>
          <a-radio :value="2">定时发布</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="formRef.publishType == 2"
        v-bind="validateInfos.fix_at"
      >
        <a-date-picker
          :disabledDate="disabledDate"
          :defaultPickerValue="publishTime"
          :disabled-time="disabledDateTime"
          :show-time="{ format: 'YYYY-MM-DD HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          :showNow="false"
           placeholder="请选择时间"

          @change="onTimeChange"
        />
        <span class="sys-timezone">（用户设置时区：{{ currentTimezoneLabel }}）</span>
      </a-form-item>
    </a-form>

    <!-- 添加描述 抽屉 -->
    <AddDecDrawer ref="AddDecDrawerRef" @updateDec="updateDec"></AddDecDrawer>

  </div>
</template>

<style lang="less" scoped>
:deep(.ss-row) {
  flex-wrap: unset;
}
:deep(.ss-form-item-has-error .ss-upload) {
  background-color: #fff;
  border-color: #ff4d4f;
}
.sys-timezone{
  margin-left: 5px;
  color:#aaa;
}

.dec_list{
    .dec_item{
        margin-bottom: 10px;
        border: 1px solid  #eee;
        padding: 5px 10px;
        border-radius: 8px;
        cursor: pointer;

        span{
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            width: auto;
        }
    }
}
</style>
